<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<style>
    .navbar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1030;
        width: 100%;
    }
    body {
        padding-top: 56px;
    }
</style>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/admin/index">助农购物 - 管理后台</a>
        <div class="navbar-nav ms-auto d-flex align-items-center">
            <ul class="navbar-nav">
                <li class="nav-item dropdown d-flex align-items-center">
                    <a class="nav-link dropdown-toggle d-flex align-items-center" href="javascript:void(0)" id="adminDropdown" role="button" 
                       data-bs-toggle="dropdown" aria-expanded="false" aria-haspopup="true" style="height: 100%;">
                        ${sessionScope.admin.realName != null && !empty sessionScope.admin.realName ? sessionScope.admin.realName : sessionScope.admin.username}
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="${pageContext.request.contextPath}/admin/user/profile">个人中心</a></li>
                        <li><a class="dropdown-item" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#changePasswordModal" onclick="event.stopPropagation();">修改密码</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="${pageContext.request.contextPath}/logout">退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label for="oldPassword" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="oldPassword" name="oldPassword" 
                               placeholder="请输入当前密码" required
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="oldPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" 
                               placeholder="请输入新密码（至少6位）" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="newPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">确认密码</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" 
                               placeholder="请再次输入新密码" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="confirmPasswordError"></div>
                    </div>
                    <div class="alert alert-danger d-none" id="changePasswordError"></div>
                    <div class="alert alert-success d-none" id="changePasswordSuccess"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="changePasswordSubmitBtn">确认修改</button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    // 确保Bootstrap下拉菜单初始化
    function initDropdowns() {
        if (typeof bootstrap === 'undefined' || !bootstrap.Dropdown) {
            setTimeout(initDropdowns, 50);
            return;
        }
        
        var dropdownElementList = document.querySelectorAll('.dropdown-toggle');
        dropdownElementList.forEach(function (dropdownToggleEl) {
            try {
                var dropdownInstance = bootstrap.Dropdown.getInstance(dropdownToggleEl);
                if (!dropdownInstance) {
                    new bootstrap.Dropdown(dropdownToggleEl);
                }
            } catch (e) {
                console.error('初始化下拉菜单失败:', e);
            }
        });
    }
    
    // 初始化修改密码功能
    function initChangePassword() {
        var changePasswordBtn = document.getElementById('changePasswordSubmitBtn');
        if (changePasswordBtn) {
            changePasswordBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                var oldPasswordInput = document.getElementById('oldPassword');
                var newPasswordInput = document.getElementById('newPassword');
                var confirmPasswordInput = document.getElementById('confirmPassword');
                
                if (!oldPasswordInput || !newPasswordInput || !confirmPasswordInput) {
                    console.error('找不到密码输入框');
                    return;
                }
                
                var oldPassword = oldPasswordInput.value.trim();
                var newPassword = newPasswordInput.value.trim();
                var confirmPassword = confirmPasswordInput.value.trim();
                
                var errorDiv = document.getElementById('changePasswordError');
                var successDiv = document.getElementById('changePasswordSuccess');
                
                // 清除之前的消息和验证状态
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                oldPasswordInput.classList.remove('is-invalid');
                newPasswordInput.classList.remove('is-invalid');
                confirmPasswordInput.classList.remove('is-invalid');
                
                // 验证输入
                var isValid = true;
                
                if (!oldPassword) {
                    oldPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('oldPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入当前密码';
                    isValid = false;
                }
                
                if (!newPassword) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入新密码';
                    isValid = false;
                } else if (newPassword.length < 6) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码长度至少6位';
                    isValid = false;
                }
                
                if (!confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '请确认新密码';
                    isValid = false;
                } else if (newPassword !== confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码和确认密码不一致';
                    isValid = false;
                }
                
                if (!isValid) {
                    if (errorDiv) {
                        errorDiv.textContent = '请检查输入信息';
                        errorDiv.classList.remove('d-none');
                    }
                    return;
                }
                
                // 禁用按钮
                var submitBtn = document.getElementById('changePasswordSubmitBtn');
                submitBtn.disabled = true;
                submitBtn.textContent = '修改中...';
                
                // 发送AJAX请求
                var params = new URLSearchParams();
                params.append('oldPassword', oldPassword);
                params.append('newPassword', newPassword);
                params.append('confirmPassword', confirmPassword);
                
                fetch('${pageContext.request.contextPath}/admin/user/changePassword', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: params.toString()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (successDiv) {
                            successDiv.textContent = data.message;
                            successDiv.classList.remove('d-none');
                        }
                        
                        // 清空表单
                        oldPasswordInput.value = '';
                        newPasswordInput.value = '';
                        confirmPasswordInput.value = '';
                        
                        // 3秒后关闭模态框
                        setTimeout(function() {
                            var modal = bootstrap.Modal.getInstance(document.getElementById('changePasswordModal'));
                            if (modal) modal.hide();
                        }, 2000);
                    } else {
                        if (errorDiv) {
                            errorDiv.textContent = data.message;
                            errorDiv.classList.remove('d-none');
                        }
                    }
                })
                .catch(error => {
                    if (errorDiv) {
                        errorDiv.textContent = '修改密码失败，请重试';
                        errorDiv.classList.remove('d-none');
                    }
                })
                .finally(() => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认修改';
                });
            });
        }
        
        // 模态框关闭时清除表单和消息
        var changePasswordModal = document.getElementById('changePasswordModal');
        if (changePasswordModal) {
            changePasswordModal.addEventListener('hidden.bs.modal', function() {
                document.getElementById('changePasswordForm').reset();
                document.getElementById('changePasswordError').classList.add('d-none');
                document.getElementById('changePasswordSuccess').classList.add('d-none');
                document.getElementById('oldPassword').classList.remove('is-invalid');
                document.getElementById('newPassword').classList.remove('is-invalid');
                document.getElementById('confirmPassword').classList.remove('is-invalid');
            });
        }
    }
    
    // DOM加载完成后初始化
    function initAll() {
        initDropdowns();
        initChangePassword();
    }
    
    // 等待页面加载完成和Bootstrap JS加载
    function waitForBootstrap() {
        if (typeof bootstrap !== 'undefined' && bootstrap.Dropdown) {
            initAll();
        } else {
            setTimeout(waitForBootstrap, 50);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForBootstrap);
    } else {
        waitForBootstrap();
    }
})();
</script>
